package com.uml.umlwork.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.uml.umlwork.dto.teacher.UmlTeacherDTO;
import com.uml.umlwork.entity.Teacher;
import com.uml.umlwork.entity.User;
import com.uml.umlwork.entity.enumeration.GenderEnum;
import com.uml.umlwork.mapper.TeacherMapper;
import com.uml.umlwork.mapper.UserMapper;
import com.uml.umlwork.service.TeacherService;
import com.uml.umlwork.vo.teacher.TeacherInfoVO;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author wuze
 * @since 2021-01-04
 */
@Service
public class TeacherServiceImpl extends ServiceImpl<TeacherMapper, Teacher> implements TeacherService {

    private final TeacherMapper teacherMapper;
    private final UserMapper userMapper;

    public TeacherServiceImpl(TeacherMapper teacherMapper, UserMapper userMapper) {
        this.teacherMapper = teacherMapper;
        this.userMapper = userMapper;
    }

    @Override
    public IPage<TeacherInfoVO> getAllTeacher(Long page, Long size) {
        List<Teacher> teachers = teacherMapper.selectList(null);
        //查询培训师
        return new Page<TeacherInfoVO>()
                .setPages(page)
                .setSize(size)
                .setTotal(teachers.size())
                .setRecords(teachers
                        .stream()
                        .map(teacher -> {
                            TeacherInfoVO vo = new TeacherInfoVO(teacher);
                            User user = userMapper.selectById(teacher.getUserId());
                            vo.setUsername(user.getUsername());
                            vo.setName(user.getName());
                            vo.setPhone(user.getPhone());
                            return vo;
                        })
                        .collect(Collectors.toList()));
    }

    @Override
    public void deleteTeacherByIdTeacher(String id) {
        teacherMapper.delete(new QueryWrapper<Teacher>().eq("user_id", id));
        userMapper.deleteById(id);
    }

    @Override
    public void updateInfo(UmlTeacherDTO dto) {
        Teacher teacher = teacherMapper.selectOne(new QueryWrapper<Teacher>().eq("user_id", dto.getId()));
        teacher.setEmail(dto.getEmail())
                .setAge(dto.getAge())
                .setGender(GenderEnum.valueOf(dto.getGender()));
        teacherMapper.updateById(teacher);
    }

    @Override
    public List<TeacherInfoVO> getTeacherByType(String type) {
        return teacherMapper.selectList(new QueryWrapper<Teacher>().eq("teacher_type", type))
                .stream().map(TeacherInfoVO::new).collect(Collectors.toList());
    }
}
